package IO_.homework;

import java.io.*;
import java.util.Scanner;

public class io10 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("请输入要查找的文件路径");
        String srcPath = in.next();
        System.out.println("请输入要查找的内容");
        String text = in.next();

        //数据校验:
        File file = new File(srcPath);
        if(!file.isDirectory()){
            System.out.println("输入的目录有误!");
            return;
        }
        checkFile(file,text);
    }

    private static void checkFile(File file, String text) {
        File[] files = file.listFiles();
        if(files==null){
            return;
        }
        for(File f:files){
            System.out.println("当前遍历的文件路径为:"+f.getAbsolutePath());
            if(f.isFile()){
                //当前是文件,进行扫描查找
                ScanFile(f,text);
            }else if(f.isDirectory()){
                //递归遍历目录文件
                checkFile(f,text);
            }else{
                return;
            }
        }
    }

    private static void ScanFile(File f, String text) {
        //读取文件内容
        try(InputStream inputStream = new FileInputStream(f)){
            StringBuffer stringBuffer = new StringBuffer();
            while(true){
                byte[] tmp = new byte[1024];
                int n = inputStream.read(tmp);
                if(n==-1){
                    break;
                }
                String s = new String(tmp, 0, n);
                stringBuffer.append(s);
            }
            if(stringBuffer.indexOf(text)==-1){
                //没找到,直接返回
                return;
            }
            System.out.println("找到了,文件路径为: "+f.getAbsolutePath());

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
